import flask
from flask import Flask, render_template, request
from hashlib import sha256
from database import Database
import requests

app = Flask(__name__)
db = Database()

secret = 'SecretKey01'


@app.route('/')
def form():
    return render_template('form.html')


@app.route('/checkout', methods=['POST', 'GET'])
def checkout():
    if request.method != 'POST':
        return render_template('form.html')

    # unpacking data from form
    amount = request.form.get('amount')
    currency = request.form.get('currency')
    description = request.form.get('description')
    shop_id = '5'
    # taking id of new order from database
    order_id = db.extract_new_id()

    # adding log to database
    db.add(order_id, float(amount), currency, description)

    if currency == 'EUR':
        # configuring data for PAY method
        data = {
            'amount': amount,
            'description': description,
            'shop_order_id': order_id,
            'shop_id': shop_id,
            'currency': '978',
        }
        # generating sign and adding it to data
        data['sign'] = generate_sign(data, 'PAY')

        return render_template('checkout.html', data=tuple(data.items()), method='PAY')

    elif currency == 'USD':
        # configuring data for BILL method
        data = {
            'shop_amount': amount,
            'description': description,
            'shop_order_id': order_id,
            'shop_id': shop_id,
            'shop_currency': '840',
            'payer_currency': '840',
        }
        # generating sign and adding it to data
        data['sign'] = generate_sign(data, 'BILL')

        # making post request with parameters
        response = requests.post('https://core.piastrix.com/bill/create', json=data)
        response_json = response.json()

        if response_json['data']:
            return flask.redirect(response_json['data']['url'])
        else:
            return render_template('error.html', error_code=response_json['message'])

    elif currency == 'RUB':
        # configuring data for INVOICE method
        data = {
            'amount': amount,
            'description': description,
            'shop_order_id': order_id,
            'shop_id': shop_id,
            'currency': '978',
            'payway': 'advcash_rub'
        }
        # generating sign and adding it to data
        data['sign'] = generate_sign(data, 'INVOICE')

        response = requests.post('https://core.piastrix.com/invoice/create', json=data)
        response_json = response.json()

        if response_json['data']:
            # extracting data from response...
            invoice_url = response_json['data']['url']
            invoice_method = response_json['data']['method']
            invoice_parameters = tuple(response_json['data']['data'].items())

            # and put it in html form by template engine.
            return render_template('checkout.html',
                                   data=invoice_parameters,
                                   method='INVOICE',
                                   invoice_url=invoice_url,
                                   invoice_method=invoice_method)
        else:
            return render_template('error.html', error_code=response_json['message'])


def generate_sign(data, method):
    methods_keys = {
        'PAY': ['amount', 'currency', 'shop_id', 'shop_order_id'],
        'BILL': ['payer_currency', 'shop_amount', 'shop_currency', 'shop_id', 'shop_order_id'],
        'INVOICE': ['amount', 'currency', 'payway', 'shop_id', 'shop_order_id']
    }

    raw_sign = ':'.join([str(data[i]) for i in methods_keys[method]]) + secret
    return sha256(raw_sign.encode('utf-8')).hexdigest()


if __name__ == '__main__':
    app.run(debug=True)